package com.zhuangxiaoyan.springboot.jpa.domian.service;

import com.zhuangxiaoyan.springboot.jpa.domian.model.User;
import com.zhuangxiaoyan.springboot.jpa.domian.repository.UserMapper;
import com.zhuangxiaoyan.springboot.jpa.domian.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * UserDomainService
 *
 * @author xjl
 * @version 2025/01/13 23:12
 **/
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据用户名查询用户
     * @return
     */
    public List<User> getAllUsersByUserMapper() {
        return userMapper.selectList(null);
    }


    /**
     * 根据 ID 查询用户
     *
     * @param id
     * @return
     */
    public Optional<User> getUserByUserMapper(int id) {
        return Optional.ofNullable(userMapper.selectById(id));
    }

    /**
     * 判断邮箱是否唯一
     *
     * @param email
     * @return
     */
    public boolean isEmailUniqueByUserMapper(String email) {
        return userMapper.findByEmail(email).isPresent();
    }


    /**
     * 判断邮箱是否唯一
     *
     * @param email
     * @return
     */
    public boolean isEmailUnique(String email) {
        return userRepository.findByEmail(email).isPresent();
    }

    /**
     * 创建用户
     *
     * @param user
     * @return
     */
    public User createUser(User user) {
        if (userRepository.findByEmail(user.getEmail()).isPresent()) {
            throw new IllegalArgumentException("Email already exists");
        }
        return userRepository.save(user);
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    public List<User> getAllUsers() {
        return (List<User>) userRepository.findAll();
    }

    /**
     * 根据 ID 查询用户
     *
     * @param id
     * @return
     */
    public Optional<User> getUserById(int id) {
        return userRepository.findById(id);
    }

    /**
     * 更新用户
     *
     * @param id
     * @param updatedUser
     * @return
     */
    public User updateUser(int id, User updatedUser) {
        return userRepository.findById(id).map(user -> {
            user.setName(updatedUser.getName());
            user.setEmail(updatedUser.getEmail());
            return userRepository.save(user);
        }).orElseThrow(() -> new IllegalArgumentException("User not found"));
    }

    /**
     * 删除用户
     *
     * @param id
     */
    public void deleteUser(int id) {
        if (!userRepository.existsById(id)) {
            throw new IllegalArgumentException("User not found");
        }
        userRepository.deleteById(id);
    }
}